package com.x.epspace.controller;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import com.weixin.publicnumber.api.SnsAPI;
import com.weixin.publicnumber.bean.SnsToken;
import com.x.epspace.common.AppConfig;
import com.x.epspace.common.CheckMobile;
import com.x.epspace.common.MessagesOper;
import com.x.epspace.common.MyThread;
import com.x.epspace.common.StringTools;
import com.x.epspace.common.Tool;
import com.x.epspace.entity.BindEnt;
import com.x.epspace.entity.Messages;
import com.x.epspace.entity.RegUser;
import com.x.epspace.ext.HandleSessionService;
import com.x.epspace.service.BindEntService;
import com.x.epspace.service.BindPaperService;
import com.x.epspace.common.MessagesService;
import com.x.epspace.service.RegService;

@Controller("MainAction")
public class MainAction extends BaseActionController {

	private static final Log log = LogFactory.getLog(MainAction.class);

	@Resource
	private HandleSessionService handleSession;

	@Resource
	private RegService regService;

	@Resource
	private BindEntService bindEntService;

	@Resource
	private BindPaperService bindPaperService;

	@Resource
	private MessagesOper messageOper;
	
	@Resource
	private MessagesService messagesService;
	
	public ModelAndView fdzxc(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("fdzxc");
		CheckMobile.check(request, response);
		return mv;
	}
	
	/**
	 * 跳转到登录页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("login");
		CheckMobile.check(request, response);
		//提取注册人数
		long reguserCount = regService.getReguserCount();
		mv.addObject("reguserCount", reguserCount);
		//获取用户微信id
		String code = request.getParameter("code");
		if(!StringTools.notNull(code)){
			mv.addObject("wxuserid", "");
			//直接跳转到登录页
			return mv;
		}
		//code不为空则
		boolean flag = regService.handleWxLogin(mv, code);
		if(!flag){
			return mv;
		}
		return toSelectBindent(request,response);
	}

	/**
	 * 注销后跳转到登录页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		regService.logout();
		return index(request, response);
	}

	/**
	 * 跳转到注册页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toReguser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("reguser");
		String wxuserid = request.getParameter("wxuserid");
		mv.addObject("wxuserid", wxuserid);
		return mv;
	}

	/**
	 * 重置密码页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toForgetpwd(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forgetpwd");
		return mv;
	}

	/**
	 * 绑定企业信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toBindent(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("login");
		String identType = request.getParameter("identType");
		identType = (identType == null)?"":identType;
		if(identType.equals(AppConfig.getProperty("zrrgd", "ident_type"))){
			mv.setViewName("bindzrrgd");
		}else if(identType.equals(AppConfig.getProperty("frgd", "ident_type"))){
			mv.setViewName("bindfrgd");
		}else if(identType.equals(AppConfig.getProperty("other", "ident_type"))){
			mv.setViewName("bindother");
		}else{
			mv.setViewName("selectgdlx");
		}
		mv.addObject("identType",identType);
		return mv;
	}

	/**
	 * 跳转到选择企业身份页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toSelectBindent(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("selectbind");
		Object regUserObj = handleSession.getVal(AppConfig.getProperty(
				"USER_SESSION_KEY", "SESSION_KEY"));
		if (regUserObj == null) {
			return index(request, response);
		}
		RegUser regUser = (RegUser) regUserObj;
		Set<BindEnt> bindentSet = regUser.getBindEnts();
		if (bindentSet.size() < 1) {
			// 没有绑定企业跳转到绑定企业
			return toBindent(request, response);
		} else if (bindentSet.size() == 1) {
			// 直接进入主界面
			Iterator<BindEnt> iter = bindentSet.iterator();
			bindEntService.setBindEntToSession(iter.next());
			return toMain(request, response);
		} else {
			// 进入选择企业身份页面
			mv.addObject("bindentSet", bindentSet);
			return mv;
		}

	}

	/**
	 * 跳转到主页面-我的信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toMain(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("main");
		boolean ismobile = CheckMobile.check(request, response);
		Object bindentObj = handleSession.getVal(AppConfig.getProperty(
				"ENT_SESSION_KEY", "SESSION_KEY"));
		if (bindentObj == null) {
			return index(request, response);
		}
		BindEnt bindEnt = (BindEnt) bindentObj;

		// add chenwen
		Object regUserObj = handleSession.getVal(AppConfig.getProperty("USER_SESSION_KEY","SESSION_KEY"));
		RegUser regUser = (RegUser) regUserObj;
		MyThread myTread = new MyThread();
		myTread.setMessageOper(messageOper);
		myTread.setRegUser(regUser);
		myTread.setBindEnt(bindEnt);
		Thread thread = new Thread(myTread);
		thread.start();

		// 公示链接
		String creditUrl = "";
		String paperUrl = "toPaper.do";
		String bsznUrl = "";
		String flfgUrl = AppConfig.getProperty("flfgUrl_pc", "funcUrl");
		String tzckUrl = AppConfig.getProperty("tzckUrl_pc", "funcUrl");
		String gssosoUrl = "";
		if (ismobile) {
			creditUrl = AppConfig.getProperty("creditUrl_mb", "funcUrl")
					.replace("QYNBXH", bindEnt.getSnbxh());
			bsznUrl = AppConfig.getProperty("bsznUrl_mb", "funcUrl");
			gssosoUrl = AppConfig.getProperty("gssosoUrl_mb", "funcUrl");
		} else {
			creditUrl = AppConfig.getProperty("creditUrl_pc", "funcUrl")
					.replace(
							"B64SNBXH",
							Tool.encryptBASE64(bindEnt.getSnbxh().getBytes(
									"utf-8")));
			
			bsznUrl = AppConfig.getProperty("bsznUrl_pc", "funcUrl");
			gssosoUrl = AppConfig.getProperty("gssosoUrl_pc", "funcUrl");
		}
		mv.addObject("menuid", "toMain");
		mv.addObject("creditUrl", creditUrl);
		mv.addObject("paperUrl", paperUrl);
		mv.addObject("bsznUrl", bsznUrl);
		mv.addObject("flfgUrl", flfgUrl);
		mv.addObject("tzckUrl", tzckUrl);
		mv.addObject("gssosoUrl", gssosoUrl);
		return mv;
	}

	/**
	 * 跳转到档案查询
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toPaper(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("");
		boolean ismobile = CheckMobile.check(request, response);
		Object bindentObj = handleSession.getVal(AppConfig.getProperty(
				"ENT_SESSION_KEY", "SESSION_KEY"));
		if (bindentObj == null) {
			return index(request, response);
		}
		BindEnt bindEnt = (BindEnt) bindentObj;
		if (ismobile) {
			String wxAuthUrl = AppConfig.getProperty("wxAuthUrl", "system");
			String mbUrl = AppConfig.getProperty("paperUrl_mb", "funcUrl");
			String appid = AppConfig.getProperty("APPID", "system");
			String directUrl = wxAuthUrl.replace("APPID", appid);
			directUrl = directUrl.replace("DIRECTURL", mbUrl);
			directUrl = directUrl.replace("STATE", bindEnt.getSnbxh());
			mv.setViewName("redirect:"+directUrl);
			return mv;
		}
		Map<String, String> returnMap = bindPaperService.getUserEntBindPaper();
		if (!returnMap.get("result").equals(
				AppConfig.getProperty("success", "return_code"))) {
			log.error("获取用户(" + bindEnt.getRegUser().getMobile() + ","
					+ bindEnt.getSqymc() + ")档案云身份失败，失败原因："
					+ returnMap.get("description"));
			return toMain(request,response);
		}
		String paperUrl_pc = AppConfig.getProperty("paperUrl_pc", "funcUrl");
		String params = returnMap.get("params");
		mv.setViewName("redirect:"+paperUrl_pc+"?params="+params);
		return mv;
	}

	/**
	 * 跳转到我的提醒页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toMymessage(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("mymessage");
		CheckMobile.check(request, response);
		List<Messages> msgList = messagesService.findAllForEnt();
		mv.addObject("menuid", "toMymessage");
		mv.addObject("msgList", msgList);
		return mv;
	}

	/**
	 * 跳转到我要办事页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toMywork(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("mywork");
		boolean ismobile = CheckMobile.check(request, response);
		String mcdjUrl = "";
		String qynbUrl = AppConfig.getProperty("qynbUrl_pc", "funcUrl");
		String qyzzgsUrl = AppConfig.getProperty("qyzzgsUrl_pc", "funcUrl");
		String ts12315Url = "";
		if (ismobile) {
			mcdjUrl = AppConfig.getProperty("mcdjUrl_mb", "funcUrl");
			ts12315Url = AppConfig.getProperty("ts12315Url_mb", "funcUrl");
		} else {
			mcdjUrl = AppConfig.getProperty("mcdjUrl_pc", "funcUrl");
			ts12315Url = AppConfig.getProperty("ts12315Url_pc", "funcUrl");
		}
		mv.addObject("menuid", "toMywork");
		mv.addObject("mcdjUrl", mcdjUrl);
		mv.addObject("qynbUrl", qynbUrl);
		mv.addObject("qyzzgsUrl", qyzzgsUrl);
		mv.addObject("ts12315Url", ts12315Url);
		return mv;
	}

	/**
	 * 跳转到通知公告页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toNotice(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("notice");
		CheckMobile.check(request, response);
		mv.addObject("menuid", "toNotice");
		return mv;
	}

	/**
	 * 跳转到系统服务页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView toSysservice(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("sysservice");
		CheckMobile.check(request, response);
		mv.addObject("menuid", "toSysservice");
		return mv;
	}
	
	public ModelAndView toMcdj(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("mcdj");
		CheckMobile.check(request, response);
		return mv;
	}

}
